<template>
  <div class="app-container">
    <el-form :model="form" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="168px">
      <el-form-item label="仓库" prop="scId">
        <el-select v-model="form.scId" placeholder="全部" clearable :style="{width: '100%'}" @change="handleScChange">
          <el-option v-for="(item, index) in ck" :key="index" :label="item.name"
                     :value="item.id"
                     :data-type="item.categoryType"> <!-- 增加 categoryType -->
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="业务类型" prop="bizType">
        <el-select v-model="form.bizType" clearable :style="{width: '100%'}" >
          <el-option label="入库" :value="0" ></el-option>
          <el-option label="出库" :value="2" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="调整原因" prop="reasonId">
        <el-select v-model="form.reasonId" clearable :style="{width: '100%'}" >
          <el-option v-for="(item, index) in reason" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item><br/>
      <el-form-item label="备注" prop="description">
        <div style="display: flex; align-items: center;">
          <textarea cols="70" rows="3" style="border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid; margin-left: 10px;" v-model="queryParams.description"/>
        </div>
      </el-form-item><br/>
      <el-form-item label="状态" prop="status" v-if="this.$route.query.id">
        <div>
          <span>{{ form.status == 0 ? '未审核' : form.status == 3 ? '审核通过' : '审核拒绝'}}</span>
        </div>
      </el-form-item><br>
      <el-form-item label="操作人" prop="createBy" v-if="this.$route.query.id">
        <div>
          <span>{{ form.createBy }}</span>
        </div>
      </el-form-item>
      <el-form-item label="操作时间" prop="createTime" v-if="this.$route.query.id">
        <div>
          <span>{{ parseTime(form.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </div>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style="margin-left: 20px">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:product:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tblStockNumAdjustSheetDetailList" @selection-change="handleSelectionChange" height="500" >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" align="left" prop="baseDataProduct.code" v-if="warehouseType === 1"/>
      <el-table-column label="商品名称" align="left" prop="baseDataProduct.name" width="150px" v-if="warehouseType === 1">
        <template slot-scope="scope">
          <el-autocomplete
            class="inline-input"
            v-model="scope.row.baseDataProduct.name"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="handleSelect(scope.row,$event)"
          >
            <template slot-scope="{ item }">
              <span>{{ item.name }}</span>
            </template>
          </el-autocomplete>
        </template>
      </el-table-column>
      <el-table-column label="商品SKU编号" align="left" prop="baseDataProduct.skuCode" width="100px" v-if="warehouseType === 1"/>
      <el-table-column label="商品外部编号" align="left" prop="baseDataProduct.externalCode" width="100px" v-if="warehouseType === 1"/>
      <el-table-column label="单位" align="left" prop="baseDataProduct.unit" width="100px" v-if="warehouseType === 1"/>
      <el-table-column label="规格" align="left" prop="baseDataProduct.spec" width="100px" v-if="warehouseType === 1"/>
      <el-table-column label="商品类目" align="left" prop="baseDataProduct.baseDataProductCategory.name" width="100px" v-if="warehouseType === 1"/>
      <el-table-column label="商品品牌" align="left" prop="baseDataProduct.baseDataProductBrand.name" width="100px" v-if="warehouseType === 1"/>

      <el-table-column label="物料编号" align="left" prop="baseDataMaterial.code" v-if="warehouseType === 2"/>
      <el-table-column label="物料名称" align="left" prop="baseDataMaterial.name" width="100px" v-if="warehouseType === 2">
        <template slot-scope="scope">
          <el-autocomplete
            class="inline-input"
            v-model="scope.row.baseDataMaterial.name"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="materialHandleSelect(scope.row,$event)"
          >
            <template slot-scope="{ item }">
              <span>{{ item.name }}</span>
            </template>
          </el-autocomplete>
        </template>
      </el-table-column>
      <el-table-column label="规格型号" align="left" prop="baseDataMaterial.specification" width="150px" v-if="warehouseType === 2"/>
      <el-table-column label="分类名称" align="left" prop="baseDataMaterial.categoryName" width="100px" v-if="warehouseType === 2"/>
      <el-table-column label="单位" align="left" prop="baseDataMaterial.purchaseUnitName" width="100px" v-if="warehouseType === 2"/>

      <el-table-column label="库存数量" prop="oriStockNum" align="center" width="100"/>
      <el-table-column label="调整库存数量" prop="stockNum" align="center" width="100">
        <template slot-scope="scope">
          <el-input v-model="scope.row.stockNum" @input="getDiffNum"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="description" align="center"  width="120">
        <template slot-scope="scope">
          <el-input v-model="scope.row.description" />
        </template>
      </el-table-column>
    </el-table>
    <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
      <h3 style="margin:0 0 15px 10px;font-weight: bolder;">合计</h3>
      <div style="display: inline-block;margin-left:50px">
        调价品种数：<input type="text" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled v-model="this.form.productNum">
      </div>
      <div style="display: inline-block;margin-left:50px">
        库存调整数量：<input type="text" style="background-color: #FFFFFF;height: 30px;width: 120px;border-radius: 5px;margin-left: 10px;border: 1px gainsboro solid" disabled v-model="this.form.diffNum">
      </div>
    </div>

    <div slot="footer" class="dialog-footer" style="text-align: center;margin: 5px">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

  </div>
</template>

<script>
import { listStockAdjustSheet, getStockAdjustSheet, addStockAdjustSheet, updateStockAdjustSheet } from "@/api/system/StockAdjustSheet";
import { listMaterialStock } from "@/api/system/MaterialStock";
import {getMaterial} from "@/api/system/Material";
import {center, customer, user} from "@/api/system/order";
import {parseTime} from "../../../utils/ruoyi";
import {listStock} from "@/api/system/stock";
import { listReason } from "@/api/system/reason";

export default {
  name: "orderAdd",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      payTypes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品下拉框
      productList: [],
      // 仓库
      ck: [],
      // 调整原因
      reason: [],
      //库存数量单详情表格数据
      tblStockNumAdjustSheetDetailList: [],
      // 商品框
      restaurants: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 根据订单ID查询订单支付方式
      payType: {
        orderId: null,
      },
      // 表单校验
      rules: {
        code: [
          {required: true, message: "编号不能为空", trigger: "blur"}
        ],
      },
      //库存数量表ID数据
      numAllList: [],
      //库存数量详情表ID数据
      numDetailAllList: [],
      //商品库存id
      productStockAllList:[],
      //销售单号
      isOrder: false,

      warehouseType: 0, // 当前仓库类型：1-商品仓库，2-物料仓库
    };
  },
  created() {
    this.getList();
  },
  methods: {
    parseTime,
    /** 查询订单详情 */
    getList() {
      this.loading = false;
      center(this.ck).then(response => {
        this.ck = response.rows;
      });
      listReason().then(response => {
        this.reason = response.rows;
      });
      this.numDetailAllList = [];
      listStockAdjustSheet({}).then(response => {
        this.numDetailAllList = response.rows;
        let list=response.rows;
        for (var i=0;i<list.length;i++){
          this.numAllList.push(list[i].id);
        }
      });
      if (this.$route.query.id != null) {
        this.isOrder = true;
        this.selectOrder(this.$route.query.id);
      }
      this.getAmount();
    },
    /** 查询订单详情 */
    selectOrder(id) {
      getStockAdjustSheet(id).then(res => {
        // 订单赋值
        this.form = res.data;
        this.gettblSaleOrderDetailList(this.form.scId);
        this.tblStockNumAdjustSheetDetailList = res.data.tblStockNumAdjustSheetDetailList;
        console.log(this.form)

        //状态值颜色判断
        if (res.data.status == 0) {
          this.statusColor = "rgb(100, 100, 100)";
        } else if (res.data.status == 3) {
          this.statusColor = "rgb(82, 196, 26)";
        } else {
          this.statusColor = "rgb(255, 0, 0)";
        }
      });
    },
    handleScChange(scId) {
      const selectedWarehouse = this.ck.find(item => item.id === scId);
      console.log(selectedWarehouse)
      if (selectedWarehouse && selectedWarehouse.categoryType !== undefined) {
        this.warehouseType = parseInt(selectedWarehouse.categoryType); // 保存当前仓库类型
        console.log(this.warehouseType)
        this.gettblSaleOrderDetailList(scId); // 获取对应数据
      }
    },
    // 商品列表
    gettblSaleOrderDetailList(scId) {
      this.tblStockNumAdjustSheetDetailList = []

      if (this.warehouseType === 1) {
        listStock({scId}).then(response => {
          this.restaurants = response.rows.map(item => ({
            value: item.productId,  // 使用商品 ID 作为 value
            name: item.productName,
            code: item.productCode,
            skuCode: item.skuCode,
            externalCode: item.externalCode,
            unit: item.unit,
            spec: item.spec,
            ProductCategory: item.productType,
            ProductBrand: item.productBrand,
            taxPrice: item.taxPrice,
            taxAmount: item.taxAmount,
            stockNum: item.stockNum,
          }));
          console.log(response)
        });
      }  else if (this.warehouseType === 2) {
        listMaterialStock({warehouseId: scId}).then(response => {
          this.restaurants = response.rows.map(item => ({
            value: item.materialId,  // 使用商品 ID 作为 value
            name: item.materialName,
            code: item.materialCode,
            stockNum: item.stockQuantity,
          }));
          console.log(response)
        });
      }
    },
    // 商品框
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length!==1;
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.code ? [row.code] : this.ids;
      this.$modal.confirm('是否确认删除该商品列表？').then(() => {
        this.tblStockNumAdjustSheetDetailList = this.tblStockNumAdjustSheetDetailList.filter(product => !ids.includes(product.id));
        this.handleSelectionChange([]); // 清空选中项
        this.$modal.msgSuccess("删除成功");
        this.form.productNum = this.tblStockNumAdjustSheetDetailList.length;
        this.getAmount();
      }).catch(() => {});
    },
    /** 商品新增按钮操作 */
    handleAdd() {
      if (this.form.scId == null || this.form.scId == ''){
        this.$modal.msgError("请先选择仓库");
        return;
      }
      const id = generateUniqueId(this.numDetailAllList);
      if (this.warehouseType === 1) {
        // 添加一个新的空商品对象到商品列表中
        this.tblStockNumAdjustSheetDetailList.push({
          baseDataProduct: {
            name: '',
            id: null,
            code: null,
            skuCode: null,
            externalCode: null,
            unit: null,
            spec: null,
            baseDataProductCategory: {name: ''},
            baseDataProductBrand: {name: ''},
          },
          id: id,
          code: null,
          name: null,
          price: null,
          oriStockNum: null,
          stockNum: null,
          orderNo: this.tblStockNumAdjustSheetDetailList.length + 1,
          description: null
        });
      }else{
        this.tblStockNumAdjustSheetDetailList.push({
          baseDataMaterial: {
            name: '',
            id: null,
            code: null,
            stockQuantity: null,
            specification: null,
            categoryName: null,
            purchaseUnitName: null,
          },
          id: id,
          code: null,
          name: null,
          price: null,
          oriStockNum: null,
          stockNum: null,
          orderNo: this.tblStockNumAdjustSheetDetailList.length + 1,
          description: null
        })
      }
      this.form.productNum = this.tblStockNumAdjustSheetDetailList.length;
    },
    handleSelect(row, item) {
      for (let i = 0; i < this.tblStockNumAdjustSheetDetailList.length; i++) {
        if (this.tblStockNumAdjustSheetDetailList[i].baseDataProduct.name === item.name){
          this.$modal.msgError("商品已存在");
          this.tblStockNumAdjustSheetDetailList[this.tblStockNumAdjustSheetDetailList.length-1].baseDataProduct = {
            name: '',
            id: null,
            code: null,
            skuCode: null,
            externalCode: null,
            unit: null,
            spec: null,
            baseDataProductCategory: {
              name: '',
              saleTaxRate: 10,
            },
            baseDataProductBrand: { name: '' },
            tblProductStock:{ stockNum: 0}
          };
          return;
        }
      }
      // 将选中的商品名称赋值给当前行的商品名称
      row.baseDataProduct.name = item.name;
      // 将选中的商品 ID 赋值给当前行的商品 ID
      row.baseDataProduct.id = item.value;
      row.productId=item.value;
      // 将选中的商品 Code 编号赋值给当前行的商品 Code 编号
      row.baseDataProduct.code = item.code;
      // 将选中的商品 SKU 编号赋值给当前行的商品 SKU 编号
      row.baseDataProduct.skuCode = item.skuCode;
      // 将选中的商品外部编号赋值给当前行的商品外部编号
      row.baseDataProduct.externalCode = item.externalCode;
      // 将选中的商品单位赋值给当前行的商品单位
      row.baseDataProduct.unit = item.unit;
      // 将选中的商品规格赋值给当前行的商品规格
      row.baseDataProduct.spec = item.spec;
      // 将选中的商品类目赋值给当前行的商品类目
      row.baseDataProduct.baseDataProductCategory.name = item.ProductCategory;
      // 将选中的商品品牌赋值给当前行的商品品牌
      row.baseDataProduct.baseDataProductBrand.name = item.ProductBrand;
      // 库存数量
      row.oriStockNum = item.stockNum;
      // 价格
      row.price = item.taxPrice;
      console.log(item)
    },
    materialHandleSelect(row, item){
      for (let i = 0; i < this.tblStockNumAdjustSheetDetailList.length; i++) {
        if (this.tblStockNumAdjustSheetDetailList[i].baseDataMaterial.name === item.name){
          this.$modal.msgError("物料已存在");
          this.tblStockNumAdjustSheetDetailList[this.tblStockNumAdjustSheetDetailList.length-1].baseDataMaterial = {
            name: '',
            id: null,
            code: null,
            specification: null,
            categoryName: null,
            purchaseUnitName: null,
          };
          this.tblStockNumAdjustSheetDetailList[this.tblStockNumAdjustSheetDetailList.length-1].oriStockNum = 0;
          return;
        }
      }
      getMaterial(item.value).then(response => {
        console.log(response)
        row.baseDataMaterial.specification = response.data.specification;
        row.baseDataMaterial.categoryName = response.data.categoryName;
        row.baseDataMaterial.purchaseUnitName = response.data.purchaseUnitName;
        row.price = response.data.standardPrice;
      });
      row.baseDataMaterial.name = item.name;
      row.baseDataMaterial.code = item.code;
      row.materialId=item.value;
      row.oriStockNum = item.stockNum;
      console.log(item)
    },
    getAmount() {
      this.getTotalNum();
    },
    // 取消按钮
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.back();
    },
    // 循环遍历，获取库存调整数量
    getDiffNum() {
      let sum = 0;
      for (let i = 0; i < this.tblStockNumAdjustSheetDetailList.length; i++) {
        const num = this.tblStockNumAdjustSheetDetailList[i].stockNum;
        if (!isNaN(num)) {
          sum += parseInt(num);
        }
      }
      console.log(sum)
      this.$set(this.form, 'diffNum', sum);
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        available: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      if (this.tblStockNumAdjustSheetDetailList.length === 0){
        if (this.warehouseType === 1) {
          this.$modal.msgError("请录入商品");
          return;
        }else{
          this.$modal.msgError("请录入物料");
          return;
        }
      }
      for (let i = 0; i < this.tblStockNumAdjustSheetDetailList.length; i++) {
        if (this.tblStockNumAdjustSheetDetailList[i].stockNum == null){
          this.$modal.msgError("第"+(i+1)+"行的调整的数量不能为空");
          return;
        }
      }
      if (this.form.bizType == null || this.form.bizType === ''){
        this.$modal.msgError("请选择业务类型");
        return;
      }
      if (this.form.reasonId == null || this.form.reasonId === ''){
        this.$modal.msgError("请选择调整原因");
        return;
      }
      if (this.$route.query.id) {
        this.form.tblStockNumAdjustSheetDetailList = this.tblStockNumAdjustSheetDetailList;
        updateStockAdjustSheet(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.back();
        });
      } else {
        const newId = generateUniqueId(this.numAllList);
        var orderCode = getOrderCode(this.numDetailAllList);
        this.form.id = newId;
        this.form.code = orderCode;
        for (let i = 0; i < this.tblStockNumAdjustSheetDetailList.length; i++) {
          this.tblStockNumAdjustSheetDetailList[i].sheetId = newId;
        }
        this.form.tblStockNumAdjustSheetDetailList = this.tblStockNumAdjustSheetDetailList;
        this.form.createBy = "系统管理员";
        this.form.createById = "1";
        this.form.updateBy = "系统管理员";
        this.form.updateById = "1";
        this.form.status = 0;
        this.form.approveBy = null;
        this.form.approveTime = null;

        console.log(this.form);
        // addStockAdjustSheet(this.form).then(response => {
        //   this.$modal.msgSuccess("新增成功");
        //   this.$store.dispatch("tagsView/delView", this.$route);
        //   this.$router.back();
        // });
      }
    },
    beforeRouteLeave(to, from, next) {
      // 设置一个标志，表示需要刷新数据
      to.meta.cksl = true;
      next();
    }
  },
};

// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}


//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="KCSL";  //库存数量
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>
